import "dart:convert";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/bill/api.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_dropdown.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_header.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class CompleteBill extends StatefulWidget {
  const CompleteBill({super.key});

  @override
  State<StatefulWidget> createState() => _CompleteBillState();

}

class _CompleteBillState extends State<CompleteBill> {
  final ScrollController _scrollController = ScrollController();
  final List<FilterHeaderItem> _headerItems = [
    FilterHeaderItem(title: "类型"),
    FilterHeaderItem(title: "收支"),
    FilterHeaderItem(title: "支付"),
    FilterHeaderItem(
      title: "数量：0",
      render: (title) {
        return Text(
          title,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        );
      },
    ),
  ];
  final List _belong = [
    {"name": "全部", "value": ""},
    {"name": "租客", "value": "1"},
    {"name": "业主", "value": "2"},
  ];
  final List _inoutFlag = [
    {"name": "全部", "value": ""},
    {"name": "收入", "value": "1"},
    {"name": "支出", "value": "2"},
  ];
  final List _payPlatForm = [
    {"name": "全部", "value": ""},
    {"name": "线下", "value": "2"},
    {"name": "线上", "value": "1"},
  ];
  Map _filter = {
    "pageNum": 1,
    "pageSize": 10,
    "status": 2,
    "belong": "",
    "inoutFlag": "",
    "payPlatForm": ""
  };
  List _list = [];
  int _total = 0;
  double _expensesTotalMoney = 0;
  double _incomeTotalMoney = 0;
  int _apartmentId = -1;
  double _availableAmount = 0;

  void _getBillList() async {
    try {
      EasyLoading.show();
      Map<String, dynamic> params = { ..._filter };
      Map resData = await billApi.getBillList(params);
      EasyLoading.dismiss();
      List data = resData["data"]["rows"] ?? [];
      setState(() {
        _headerItems.last.title = "数量：${resData["data"]["total"] ?? 0}";
        _list.addAll(data);
        _total = resData["data"]["total"] ?? 0;
        _expensesTotalMoney = _toDouble(resData["data"]["expensesTotalMoney"]);
        _incomeTotalMoney = _toDouble(resData["data"]["incomeTotalMoney"]);
        print("ssss:>>> $_total");
        print("ssss:>>> $data");
      });
    } catch(error) {
      EasyLoading.dismiss();
      print(error);
    }
  }

  /* 获取可提现金额 */
  void _getAvailableAmount() async {
    if (_apartmentId == -1) {
      return;
    }
    Map result = await billApi.getUnwithdrawAmount(_apartmentId);
    setState(() {
      _availableAmount = result["data"];
    });
  }

  double _toDouble(dynamic data) {
    try {
      if (data is int || data is num) {
        return data.toDouble();
      } else if (data is String) {
        return double.parse(data);
      } else if (data is double) {
        return data;
      }
    } catch (error) {
      print("toDouble error:>>>>> $error");
    }

    return 0;
  }

  String formatCurrency(double amount) {
    // 首先，使用toStringAsFixed将double转换为字符串，并保留两位小数
    String numberStr = amount.toStringAsFixed(2);

    // 分割整数部分和小数部分
    List<String> parts = numberStr.split(".");
    String integerPart = parts[0];
    String decimalPart = parts.length > 1 ? ".${parts[1]}" : "";

    // 使用正则表达式和replaceAllMapped在整数部分插入千分位分隔符
    String formattedIntegerPart = integerPart.replaceAllMapped(
        RegExp(r"(?<=\d)(?=(\d{3})+(?!\d))"),
            (match) => ","
    );

    // 拼接整数部分和小数部分
    return formattedIntegerPart + decimalPart;
  }

  Widget _littleRow({ required String label, required String value }) {
    return Row(
      children: [
        Text("$label：", style: const TextStyle(fontSize: 12),),
        Text(value, style: const TextStyle(fontSize: 12),),
      ],
    );
  }

  Widget _renderEmpty() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(Icons.hourglass_empty_outlined, color: ThemeVars.colorPrimaryLight, size: 80,),
          SizedBox(height: 50,),
          Text("温馨提示：可以在【入住详情】中添加待收账单", style: TextStyle(fontSize: 12, color: ThemeVars.colorTextSec),),
        ],
      ),
    );
  }

  String _getBuildingAndRoomName(room) {
    if (room != null) {
      String buildingName = room["buildingName"] ?? "";
      String roomName = room["name"] ?? "";
      String name = "$buildingName$roomName";
      if (name.isEmpty) return "--";
      return name;
    }
    return "--";
  }

  Future<void> _refresh() async {
    setState(() {
      _list = [];
      _filter["pageNum"] = 1;
    });
    _getBillList();
  }

  void _onScroll() {
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      print("判断前：》》》${_list.length} --- $_total");
      if (_list.length < _total) {
        setState(() {
          _filter["pageNum"] += 1;
        });
        _getBillList();
      }
    }
  }

  @override
  void initState() {
    super.initState();
    String apartment = storage.getString("apartment") ?? "";
    if (apartment != "") {
      _apartmentId = jsonDecode(apartment)["apartmentId"] ?? -1;
    }
    _refresh();
    _getAvailableAmount();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FilterLayout(
          headerItems: _headerItems,
          dropdownItems: [
            FilterDropdownItem(
              items: _belong,
              itemAsString: (item) => item["name"],
              onChanged: (item) =>
                setState(() {
                  _headerItems[0].title = item["name"];
                  _filter["belong"] = item["value"];
                  _refresh();
                }),
            ),
            FilterDropdownItem(
              items: _inoutFlag,
              itemAsString: (item) => item["name"],
              onChanged: (item) =>
                  setState(() {
                    _headerItems[1].title = item["name"];
                    _filter["inoutFlag"] = item["value"];
                    _refresh();
                  }),
            ),
            FilterDropdownItem(
              items: _payPlatForm,
              itemAsString: (item) => item["name"],
              onChanged: (item) =>
                  setState(() {
                    _headerItems[2].title = item["name"];
                    _filter["payPlatForm"] = item["value"];
                    _refresh();
                  }),
            ),
          ],
          child: Stack(
            children: [
              RefreshIndicator(
                onRefresh: _refresh,
                child: _list.isNotEmpty ? ListView.separated(
                  controller: _scrollController,
                  padding: const EdgeInsets.fromLTRB(ThemeVars.paddingPage, 48, ThemeVars.paddingPage, ThemeVars.paddingPage + 80),
                  itemCount: _list.length,
                  itemBuilder: (context, index) {

                    Map item = _list[index];
                    Map room = item["room"] ?? {};
                    return Container(
                      decoration: const BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(8)),
                      ),
                      child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {

                        },
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
                              child: Text(item["name"], style: const TextStyle(fontSize: 16), textAlign: TextAlign.left,),
                            ),
                            const SolidDivider(padding: EdgeInsets.only(left: ThemeVars.paddingPage),),
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: ThemeVars.paddingPage),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.stretch,
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      _littleRow(label: "支付时间", value: DateTools.formatYMD(item["updateTime"])),
                                      Text(
                                        "${item["inoutFlag"] == "1" ? "+" : "-"}${formatCurrency(item["money"])}",
                                        style: TextStyle(color: item["inoutFlag"] == "1" ? ThemeVars.colorSuccess : ThemeVars.colorError),
                                      )
                                    ],
                                  ),
                                  SizedBox(height: 4,),
                                  _littleRow(label: "账单周期", value: "${DateTools.formatYMD(item["billCycleBegin"])} - ${DateTools.formatYMD(item["billCycleEnd"])}"),
                                  SizedBox(height: 4,),
                                  Text(_getBuildingAndRoomName(room))
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                    );
                  },
                  separatorBuilder: (context, index) => const SizedBox(height: 15),
                )
                    : _renderEmpty(),
              ),
              Positioned(
                top: 0,
                left: 0,
                width: MediaQuery.of(context).size.width,
                child: Container(
                  height: 48,
                  padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage),
                  decoration: BoxDecoration(
                    color: ThemeVars.colorBackground,
                    // color: Colors.white,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      // Container(
                      //   padding: EdgeInsets.fromLTRB(12, 2, 6, 2),
                      //   decoration: BoxDecoration(
                      //       color: ThemeVars.colorDisabled,
                      //       borderRadius: BorderRadius.all(Radius.circular(20))
                      //   ),
                      //   child: const Row(
                      //     children: [
                      //       Text("时间筛选", style: TextStyle(color: Colors.white,),),
                      //       Icon(Icons.arrow_drop_down, color: Colors.white,)
                      //     ],
                      //   ),
                      // ),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Row(
                            children: [
                              Text("收入：", style: TextStyle(color: ThemeVars.colorTextSec, fontSize: 11,),),
                              Text(formatCurrency(_incomeTotalMoney), style: TextStyle(color: ThemeVars.colorSuccess, fontSize: 11,),)
                            ],
                          ),
                          Row(
                            children: [
                              Text("支出：", style: TextStyle(color: ThemeVars.colorTextSec, fontSize: 11,),),
                              Text(formatCurrency(_expensesTotalMoney), style: TextStyle(color: ThemeVars.colorError, fontSize: 11,),)
                            ],
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              ),
              // 底部固定提现栏
              Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: Container(
                  padding: const EdgeInsets.all(ThemeVars.paddingPage),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.1),
                        offset: const Offset(0, -2),
                        blurRadius: 8,
                        spreadRadius: 0,
                      ),
                    ],
                  ),
                  child: Row(
                    children: [
                      // 左侧提示
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              "可提现：¥${formatCurrency(_availableAmount)}",
                              style: const TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                            const Text(
                              "提现将在1-3个工作日内到账",
                              style: TextStyle(
                                fontSize: 12,
                                color: ThemeVars.colorTextSec,
                              ),
                            ),
                          ],
                        ),
                      ),
                      // 右侧提现按钮
                      SizedBox(
                        width: 120,
                        child: ElevatedButton(
                          onPressed: _availableAmount > 0 ? () {
                            Stacker.pushNamed(Keys.WITHDRAW);
                          } : null,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: ThemeVars.colorPrimary,
                            foregroundColor: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                            padding: const EdgeInsets.symmetric(vertical: 12),
                          ),
                          child: const Text(
                            "提现",
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          )
      ),
    );
  }

}
